package top.onedream.buildsmallsoftware.repo

import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import top.onedream.buildsmallsoftware.model.user.User

/**
 * 用户存储库
 * @author zhangkein
 * @date 2023/05/16
 * @constructor 创建[UserRepository]
 */
@Repository
interface UserRepository : CrudRepository<User, Long> {

    /**
     * 找到所有
     * @param [pageable] 可分页
     * @return [Page<User?>?]
     */
    fun findAll(pageable: Pageable?): Page<User?>?


    /**
     * 找到用户名
     * @param [username] 用户名
     * @return [User?]
     */
    fun findByUsername(username: String): User?

    /**
     * 更新用户根据用户名
     * @param [user] 用户
     * @return [User?]
     */
    @Modifying
    @Query(
        "update User as u set" +
                " u.age = case when :#{#user.age} is not null then :#{#user.age} else u.age end ," +
                " u.nickname = case when :#{#user.nickname} is not null then :#{#user.nickname} else u.nickname end " +
                " where u.username = :#{#user.username}"
    )
    fun customUpdateUserByUsername(@Param("user") user: User): User?


    /**
     * 找到用户通过用户名和年龄
     * @param [username] 用户名
     * @param [age] 年龄
     * @return [List<User>]
     */
    fun findUsersByUsernameAndAge(username: String?, age: Int?): List<User>
}
